<script setup lang="ts">
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import * as userApi from '@/api/user'
import * as accountApi from '@/api/account'
import Modal from '@/components/Modal/index.vue'
import dayjs from 'dayjs'
const route = useRoute()
// 提醒设置
let txCheckedList = ref<Array<string>>([])
const txOptions = [
  { label: '平台登录异常提醒', value: '1' },
  { label: '出票失败提醒', value: '2' },
  { label: '出票成功提醒', value: '3' },
  // { label: '每日业务总结', value: '4' },
  { label: '闲鱼无意图消息提醒', value: '5' },
  { label: '微信无意图消息提醒', value: '6' },
  { label: '创建订单失败提醒', value: '7' },
]
const txChange = (e: any) => {
  console.log('提醒=', txCheckedList.value)
}
// 提醒渠道
let txqdValueList = ref<Array<string>>([])
const txqdOptions = [
  { label: '企微机器人', value: '1' },
  { label: '钉钉机器人', value: '2' },
]
let ddKey = ref<string>('')
let qwKey = ref<string>('')
let balanceErrorAmount = ref<any>('')
let balanceErrorRemind = ref<boolean>(false)

const formRef = ref()
let labelCol = { span: 5 }
interface FormState {
  appkey: string
  appSerect: string
}
const formState = reactive<FormState>({
  appkey: '',
  appSerect: '',
})
import type { Rule } from 'ant-design-vue/es/form'
const rules: Record<string, Rule[]> = {
  appkey: [{ required: true, message: '良票appkey', trigger: 'blur' }],
  appSerect: [{ required: true, message: '良票appSerect', trigger: 'blur' }],
}

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  // console.log(page, pageSize)
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true,
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  wechatId?: string | undefined
  nickName?: string | undefined
  remark?: string | undefined
  groupId?: string
  expireState?: string | number
  robotState?: string | number
  updateState?: string | number
  wechatState?: string | number
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '序号',
    key: 'id',
    width: 300,
    algin: 'center',
  },
  {
    title: '钉钉机器人Key',
    key: 'dingTalkRobotKey',
    width: 300,
    algin: 'center',
  },
  {
    title: '消息提醒类型',
    key: 'messageRemindType',
    width: 300,
  },
  {
    title: '微信机器人Key',
    key: 'wecomRobotKey',
    width: 350,
  },
  {
    title: '备注',
    key: 'remark',
    width: 300,
  },
  {
    title: '创建/过期时间',
    key: 'createTime',
    width: 400,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right',
  },
]
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize

  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await accountApi.getUserSettingList(searchParams.value)
    if (state === 200) {
      // data.list.forEach((item: { isRemarkShow: boolean }) => {
      //   item.isRemarkShow = false
      // })
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

const saveSystem = async () => {
  const params = {
    loginErrorRemind: 0,
    outTicketErrorRemind: 0,
    outTicketSucceedRemind: 0,
    fishNullifyMessageRemind: 0,
    wechatNullifyMessageRemind: 0,
    wecomRobotOnOff: 0,
    dingTalkRobotOnOff: 0,
    orderErrorRemind: 0,
    balanceErrorAmount: balanceErrorAmount.value * 100,
    // orderErrorRemind: orderErrorRemind.value ? 1 : 0,
    balanceErrorRemind: balanceErrorRemind.value ? 1 : 0,
    // platformKey: '',
    // platformSecret: '',
  }
  txCheckedList.value.forEach(item => {
    // 平台登录异常提醒
    if (item == '1') {
      params.loginErrorRemind = 1
    }
    // 出票失败提醒
    if (item == '2') {
      params.outTicketErrorRemind = 1
    }
    if (item == '7') {
      params.orderErrorRemind = 1
    }
    // 出票成功提醒
    if (item == '3') {
      params.outTicketSucceedRemind = 1
    }
    // 闲鱼无意图消息提醒
    if (item == '5') {
      params.fishNullifyMessageRemind = 1
    }
    // 微信无意图消息提醒
    if (item == '6') {
      params.wechatNullifyMessageRemind = 1
    }
  })
  txqdValueList.value.forEach(item => {
    // 企微机器人
    if (item == '1') {
      params.wecomRobotOnOff = 1
      params.wecomRobotKey = qwKey.value
    }
    // 钉钉机器人
    if (item == '2') {
      params.dingTalkRobotOnOff = 1
      params.dingTalkRobotKey = ddKey.value
    }
  })

  formRef.value.validate().then(async () => {
    // console.log('formState=', formState)
    // params.platformKey = formState.appkey
    // params.platformSecret = formState.appSerect
    try {
      const res = await userApi.settingUserSystem(params)
      if (res.state == 200) {
        message.success('保存成功')
      } else {
        message.error(res.message)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
  })
}

const updatedMessageRef = ref(null)
const AssociatedMessageRef = ref(null)
const addMessageRef = ref(null)

const MessageTypeForm = ref({
  dingTalkRobotKey: '',
  remark: '',
  wecomRobotKey: '',
  id: '',
})
const associatedMessageForm = ref({
  id: '',
  messageRemindType: '',
})

const addMessageTypeForm = ref({
  dingTalkRobotKey: '',
  remark: '',
  wecomRobotKey: '',
})

//全选按钮
const allIn = ref(false)
const allInChange = e => {
  console.log(e.target.checked, 'e')
  if (e.target.checked) {
    RemindSettingValueList.value = RemindSettingList.value.map(item => item.value)
  } else {
    RemindSettingValueList.value = []
  }
}
//添加消息
const addMessage = (e: any) => {
  console.log(e, 'eee')
  addMessageTypeForm.value.dingTalkRobotKey = ''
  addMessageTypeForm.value.wecomRobotKey = ''
  addMessageTypeForm.value.remark = ''
  addMessageRef?.value.setVisible(true)
}
//修改通知方式确认按钮
const addMessageConfirm = async () => {
  try {
    const result = await accountApi.addUserSettingFun(addMessageTypeForm.value)
    if (result.state == 200) {
      message.success('添加成功')
      getList()
      addMessageRef?.value.setVisible(false)
    } else {
      message.error(result.message)
    }
  } catch (error) {
    message.error('操作失败~')
  }
}
const updatedMessage = (e: any) => {
  console.log(e, 'eee')
  MessageTypeForm.value.id = e.id
  MessageTypeForm.value.dingTalkRobotKey = e.dingTalkRobotKey
  MessageTypeForm.value.wecomRobotKey = e.wecomRobotKey
  MessageTypeForm.value.remark = e.remark
  updatedMessageRef?.value.setVisible(true)
}
//修改通知方式确认按钮
const updatedMessageConfirm = async () => {
  try {
    const result = await accountApi.updateUserSettingFun(MessageTypeForm.value)
    if (result.state == 200) {
      message.success('修改成功')
      getList()
      updatedMessageRef?.value.setVisible(false)
    } else {
      message.error(result.message)
    }
  } catch (error) {
    message.error('操作失败~')
  }
}
const AssociatedMessage = async (e: any) => {
  console.log(e, 'eee')
  associatedMessageForm.value.id = e.id
  RemindSettingValueList.value = e.messageRemindType.split(',')
  AssociatedMessageRef?.value.setVisible(true)
}
const AssociatedMessageConfirm = async () => {
  associatedMessageForm.value.messageRemindType = RemindSettingValueList.value.join(',')
  try {
    const result = await accountApi.updateAssociatedMessage(associatedMessageForm.value)
    if (result.state == 200) {
      message.success('修改成功')
      getList()
      AssociatedMessageRef?.value.setVisible(false)
    } else {
      message.error(result.message)
    }
  } catch (error) {
    message.error('操作失败~')
  }
}
//删除对应的渠道
const del = async (e: any) => {
  try {
    const result = await accountApi.delAssociateRemindFun({ id: e.id })
    if (result.state == 200) {
      message.success('删除成功')
      getList()
    } else {
      message.error(result.message)
    }
  } catch (error) {
    message.error('操作失败~')
  }
}
//获取系统消息
const getSystem = async () => {
  try {
    let { state, data, message: msg } = await userApi.getUserSetting()
    if (state === 200) {
      formState.appkey = data.platformKey
      formState.appSerect = data.platformSecret
      balanceErrorRemind.value = data.balanceErrorRemind ? true : false
      balanceErrorAmount.value = data.balanceErrorAmount ? data.balanceErrorAmount / 100 : 0
      // orderErrorRemind.value = data.orderErrorRemind ? true : false

      // 平台登录异常提醒
      if (data.loginErrorRemind == 1) {
        txCheckedList.value.push('1')
      }
      // 出票失败提醒
      if (data.outTicketErrorRemind == 1) {
        txCheckedList.value.push('2')
      }
      // 出票成功提醒
      if (data.outTicketSucceedRemind == 1) {
        txCheckedList.value.push('3')
      }
      // 闲鱼无意图消息提醒
      if (data.fishNullifyMessageRemind == 1) {
        txCheckedList.value.push('5')
      }
      // 微信无意图消息提醒
      if (data.wechatNullifyMessageRemind == 1) {
        txCheckedList.value.push('6')
      }
      //创建订单失败提醒
      if (data.orderErrorRemind) {
        txCheckedList.value.push('7')
      }
      // 企微机器人
      if (data.wecomRobotOnOff == 1) {
        txqdValueList.value.push('1')
      }
      qwKey.value = data.wecomRobotKey
      // 钉钉机器人
      if (data.dingTalkRobotOnOff == 1) {
        txqdValueList.value.push('2')
      }
      ddKey.value = data.dingTalkRobotKey
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

const RemindSettingList = ref([])
let RemindSettingValueList = ref<Array<string>>([])

//获取当前的 消息类型集合
const getRemindSettingListFun = async () => {
  try {
    const result = await accountApi.getRemindSettingListFun()
    if (result.state == 200) {
      RemindSettingList.value = result.data
    } else {
      message.error(result.message)
    }
  } catch (error) {
    message.error('操作失败~')
  }
}
// 登录

onMounted(() => {
  getSystem()
  getList()
  getRemindSettingListFun()
})
</script>

<template>
  <page-container :title="route.meta.title">
    <a-card style="overflow-x: scroll">
      <!-- <div class="rowBox">
        <span class="label-1">提醒设置：</span>
        <a-checkbox-group v-model:value="txCheckedList" :options="txOptions" @change="txChange" />
      </div>

      <div class="rowBox">
        <span class="label-1">提醒渠道：</span>
        <a-checkbox-group v-model:value="txqdValueList">
          <a-checkbox v-for="(item, index) in txqdOptions" :key="index" :value="item.value">
            <span>{{ item.label }}</span>
          </a-checkbox>
        </a-checkbox-group>
      </div>

      <div class="rowBox" v-if="txqdValueList.includes('1')">
        <span class="label-1"></span>
        <span>企微机器人key：</span>
        <a-input v-model:value="qwKey" style="width: 400px"></a-input>
      </div>

      <div class="rowBox" v-if="txqdValueList.includes('2')">
        <span class="label-1"></span>
        <span>钉钉机器人key：</span>
        <a-input v-model:value="ddKey" style="width: 400px"></a-input>
      </div> -->
      <div style="display: flex; align-items: center">
        <div class="rowBox1">
          <span class="label-1">余额阈值提醒：</span>
          <a-switch v-model:checked="balanceErrorRemind" />
        </div>
        <div class="rowBox1" v-if="balanceErrorRemind">
          <span class="label-1">预警金额：</span>
          <a-input
            v-model:value="balanceErrorAmount"
            type="number"
            style="width: 120px"
            suffix="元"
          ></a-input>
        </div>
        <a-form
          ref="formRef"
          :rules="rules"
          :model="formState"
          :label-col="labelCol"
          style="width: 540px"
        >
          <div style="display: flex; align-items: center; margin-bottom: 15px; margin-left: 50px">
            <a-button type="primary" style="border-radius: 6px" @click="saveSystem">保存</a-button>
          </div>
        </a-form>
      </div>
    </a-card>
    <div style="height: 10px"></div>
    <a-card>
      <a-button type="primary" style="border-radius: 6px" @click="addMessage">
        添加通知渠道
      </a-button>
      <div style="height: 10px"></div>

      <a-table
        style="overflow-x: scroll"
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        :loading="loading"
        @change="changePage"
        rowKey="id"
        size="small"
        :scroll="{ x: 100 }"
      >
        <template #emptyText>
          <a-empty description="暂无数据" />
        </template>

        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'id'">
            <div style="width: 150px">{{ index + 1 }}</div>
          </template>
          <template v-if="column.key === 'messageRemindType'">
            <div style="width: 150px">{{ record.messageRemindTypeText }}</div>
          </template>
          <template v-if="column.key === 'wecomRobotKey'">
            <div style="width: 150px">{{ record.wecomRobotKey }}</div>
          </template>
          <template v-if="column.key === 'dingTalkRobotKey'">
            <div style="width: 150px">{{ record.dingTalkRobotKey }}</div>
          </template>
          <template v-if="column.key === 'remark'">
            <div style="width: 150px">{{ record.remark }}</div>
          </template>
          <template v-if="column.key === 'createTime'">
            <div style="width: 150px">
              {{ dayjs(Number(record.createTime)).format('YYYY-MM-DD HH:mm:ss') }}
            </div>
          </template>

          <template v-else-if="column.key === 'action'">
            <div style="display: flex; flex-direction: column">
              <a @click="updatedMessage(record)">修改通知渠道</a>
              <a @click="AssociatedMessage(record)">关联消息类型</a>

              <a-popconfirm
                title="确定要删除吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="del(record)"
              >
                <a>删除</a>
              </a-popconfirm>
            </div>
          </template>
        </template>
      </a-table>
      <Modal
        title="修改通知渠道"
        :width="800"
        :height="500"
        ref="updatedMessageRef"
        @onConfirmAdd="updatedMessageConfirm"
      >
        <template #contentValue>
          <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 20 }" style="padding-left: 60px">
            <a-form-item label="钉钉机器人key" name="dingTalkRobotKey">
              <a-input
                v-model:value="MessageTypeForm.dingTalkRobotKey"
                placeholder="钉钉机器人key"
              ></a-input>
            </a-form-item>

            <a-form-item label="企微机器人key" name="wecomRobotKey">
              <a-input
                v-model:value="MessageTypeForm.wecomRobotKey"
                placeholder="企微机器人key"
              ></a-input>
            </a-form-item>
            <a-form-item label="备注" name="remark">
              <a-input
                style="width: 50%"
                v-model:value="MessageTypeForm.remark"
                placeholder="备注"
              ></a-input>
            </a-form-item>
          </a-form>
        </template>
      </Modal>

      <Modal
        title="添加通知渠道"
        :width="800"
        :height="500"
        ref="addMessageRef"
        @onConfirmAdd="addMessageConfirm"
      >
        <template #contentValue>
          <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 20 }" style="padding-left: 60px">
            <a-form-item label="钉钉机器人key" name="dingTalkRobotKey">
              <a-input
                v-model:value="addMessageTypeForm.dingTalkRobotKey"
                placeholder="钉钉机器人key"
              ></a-input>
            </a-form-item>

            <a-form-item label="企微机器人key" name="wecomRobotKey">
              <a-input
                v-model:value="addMessageTypeForm.wecomRobotKey"
                placeholder="企微机器人key"
              ></a-input>
            </a-form-item>
            <a-form-item label="备注" name="remark">
              <a-input
                style="width: 50%"
                v-model:value="addMessageTypeForm.remark"
                placeholder="备注"
              ></a-input>
            </a-form-item>
          </a-form>
        </template>
      </Modal>
      <Modal
        title="关联消息类型"
        :width="600"
        :height="500"
        ref="AssociatedMessageRef"
        @onConfirmAdd="AssociatedMessageConfirm"
      >
        <template #contentValue>
          <a-checkbox :value="allIn" @change="allInChange">
            <span>全选</span>
          </a-checkbox>
          <a-checkbox-group v-model:value="RemindSettingValueList">
            <a-checkbox v-for="(item, index) in RemindSettingList" :key="index" :value="item.value">
              <span>{{ item.type }}</span>
            </a-checkbox>
          </a-checkbox-group>
        </template>
      </Modal>
      <!-- <Modal title="" ref="updatedMessageRef"></Modal> -->
    </a-card>
  </page-container>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  width: 1000px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

a:hover {
  color: red;
}

.rowBox {
  display: flex;
  margin-bottom: 15px;
  // background: pink;
}

.rowBox1 {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.label-1 {
  width: 140px;
  text-align: right;
  line-height: 30px;
  padding-right: 5px;
}

.iptWidth {
  width: 500px;
}
</style>
